package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"syscall"
	"time"
)

const (
	defaultMounted      = "/atlas/dq2"
	defaultSiteSizeFile = "site-size"
	usage               = "ub -m=/atlas/dq2"
	timeFormat          = "2006-01-02T15:04:05"
)

/*
	Need to match the structure of a JSON for Marshal to expected form
*/
type L1 struct {
	Total     uint64
	Available uint64
}

type L0 struct {
	Size L1
	Time string
}

func main() {
	mnt := flag.String("m", defaultMounted, usage)
	flag.Parse()

	buf := new(syscall.Statfs_t)
	ff, _ := os.Open(*mnt)
	fd := ff.Fd()
	syscall.Fstatfs(int(fd), buf)

	dfTotal := buf.Blocks * uint64(buf.Bsize)
	dfAvail := buf.Bavail * uint64(buf.Bsize)
	//t := time.Now().UTC().Format(time.RFC3339)
	t := time.Now().UTC().Format(timeFormat)
	s1 := L1{
		Total:     dfTotal,
		Available: dfAvail,
	}

	s0 := L0{
		Size: s1,
		Time: t,
	}
	b1, err := json.Marshal(s0)
	if err != nil {
		fmt.Println("error", err)
	}
	os.Stdout.Write(b1)
}

/*
	http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go?s=1667:1878#L107

	http://www.ietf.org/rfc/rfc3339.txt
	date-time       = full-date "T" full-time
	--
	http://golang.org/doc/install/source
	--
	pushd $HOME
	export GOROOT=$HOME/go
	export PATH=$PATH:$GOROOT/bin
	hg clone -u release https://code.google.com/p/go
	cd go/src;./all.bash
	popd;go build ub.go
	./ub -m=/atlas/dq2 > /tmp/site-size

cat /atlas/dq2/site-size |/usr/bin/json_verify
crontab -l
@hourly /bin/nice /etc/misc/ub > /atlas/dq2/site-size


*/
/*
	donmoore@utdallas.edu


	This file is part of ub.go.

    ub.go is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ub.go is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ub.go.  If not, see <http://www.gnu.org/licenses/>.
*/
